package com.zhou.piledriver.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhou.piledriver.service.MqttService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.zhou.piledriver.config.MqttConfig.INPUT_DATA;

/**
 * @author ZhouShenBin
 * @date 2024/3/20 15:41
 * @description
 */

@Slf4j
@Component
public class MqttHandler {
    @Resource
    private MqttService mqttService;
    @ServiceActivator(inputChannel = INPUT_DATA)
    @Async("mqttExecutor")
    public void handler(Message<byte[]> in) throws InterruptedException {
        String topic = Objects.requireNonNull(in.getHeaders().get("mqtt_receivedTopic")).toString();
        JSONObject jsonObject = JSONUtil.parseObj(new String(in.getPayload()));
        if (topic.matches("mix/r/(.*)")) {
//            String deviceCode = topic.split("/")[2];
            mqttService.handlerRecord((jsonObject));
        } else if(topic.matches("mix/h/(.*)")){
            mqttService.handlerHeartbeat((jsonObject));
        }else {
            System.out.println("丢弃消息：主题[" + topic  + "]，负载：" + jsonObject);
        }
    }
}
